<?php
class DomMonitorAnalyzer {
	
	public static function getLatestRequests() {
		return DomSql::selectQuery('SELECT * FROM dom_monitor_overall_log ORDER BY id DESC LIMIT 50');
	}
	
	public static function getLatestNotFinishedRequests() {
		return DomSql::selectQuery('SELECT * FROM dom_monitor_overall_log WHERE finished = 0 ORDER BY id DESC LIMIT 20');
	}
	
	public static function getLatestErrors() {
		return DomSql::selectQuery('SELECT * FROM dom_monitor_overall_log WHERE error = 1 ORDER BY id DESC LIMIT 20');
	}
	
	public static function getLatestSlowQueries() {
		return DomSql::selectQuery('SELECT *
			FROM dom_monitor_sql_log as s
			JOIN dom_monitor_overall_log as l ON (s.overallLogId = l.id)
			WHERE queryTime > 2
			ORDER BY s.id DESC LIMIT 20');
	}
	
	public static function getLatestHosts() {
		return DomSql::selectQuery('
			SELECT ip, count(1) as total FROM(
				SELECT ip 
				FROM dom_monitor_overall_log 
				ORDER BY id DESC 
				LIMIT 2500
			) as x
			GROUP BY ip
			ORDER BY total DESC
			LIMIT 25
		');
	}
	
	public static function getHtmlReport() {
	
		$report = '<pre>';
		
		$report .= '<h1>Latest requests</h1>';
		$report .= self::dataToHtmlTable( self::getLatestRequests() );
		
		$report .= '<h1>Latest hosts</h1>';
		$report .= self::dataToHtmlTable( self::getLatestHosts() );
		
		$report .= '<h1>Latest not finished requests</h1>';
		$report .= self::dataToHtmlTable( self::getLatestNotFinishedRequests() );
		
		$report .= '<h1>Latest errors</h1>';
		$report .= self::dataToHtmlTable( self::getLatestErrors() );
		
		$report .= '<h1>Latest slow queries</h1>';
		$report .= self::dataToHtmlTable( self::getLatestSlowQueries() );
	
		$report .= '</pre>';
		return $report;
	}
	
	private static function dataToHtmlTable( $data ) {
		$headers = '';
		$report = '';
		foreach( $data as $line ) {
			if( $headers == '' ) {
				foreach( $line as $key => $value ) {
					$headers .= '<td>'.$key.'</td>';
				}
			}
			$report.= '<tr>';
			foreach( $line as $value ) {
				$report .= '<td>'.$value.'</td>';
			}
			$report.= '</tr>';
		}
		return '<table border="1" cellspacing="0" cellpadding="2"><tr>'.$headers.'</tr>'.$report.'</table>';
	}

}